#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <wait.h>


/*
void run_child()
{
    int cnt = 5;
    while(cnt--)
    {
        printf("i am child process, pid: %d, ppid: %d\n",getpid(), getppid());
        sleep(1);
    }
}

int main()
{
    for(int i = 1; i <= 10; i++)
    {
        pid_t id = fork();
        if(id == 0)
        {
            run_child();
            exit(0);
        }
        printf("create child process: %d success\n",id);
    }
    
    sleep(10);
    for(int i = 1; i <= 10; i++)
    {
       pid_t id  = wait(NULL);
       if(id > 0)
       {
           printf("wait %d success",id);
       }
    }
    
    sleep(10);
    return 0;
}*/


int main()
{
    int id = fork();
    if(id < 0)
    {
        perror("fork");
        return 1;
    
    }
    else if(id == 0)
    {
        //child
        int cnt = 5;
        while(cnt--)
        {
            printf("i am child, pid: %d, ppid: %d, cnt: %d\n", getpid(), getppid(),cnt);
            sleep(1);
        }
        exit(10);
    }
    else 
    {
        //parent
        int cnt = 10;
        while(cnt--)
        {
            printf("i am parent, pid: %d, ppid: %d, cnt: %d\n", getpid(), getppid(),cnt);
            sleep(1);
        }
       // int pid = wait(0);
        //int pid = waitpid(-1, NULL, 0); // 这和wait一样
        int ret = 0;
        while(1)
        {

            int pid = waitpid(-1, &ret, WNOHANG);
            if(id > 0)
            {
                //printf("wait pid: %d success, sigcode: %d, exitcode: %d\n",pid,ret & 0x7f, (ret >> 8) & 0xff);
                if(WIFEXITED(ret))
                {
                    printf("正常\n");
                }
                else 
                {
                    printf("有问题\n");
                }
                break;
            }
            else if(id < 0)
            {
                printf("wait fail!");
                break;
            }
            else 
            {
                printf("等一下我，还没好\n");
            }
        }
        sleep(5);
    }



    return 9;
}
